const Router = require('koa-router')
const {userLogin} = require('../controllers/index.js')
const { sign } = require('../utils/jwt.js')

const router = new Router()

router.prefix('/user')

// 登录接口
router.post('/login',async(ctx,next) => {
    const { username , password } = ctx.request.body  // post请求数据
    //console.log(username,password)
    try {
        const res = await userLogin(username, password)
        //console.log(res)
        if (res.length) {  // 账号密码正确
          const data = {
            username: res[0].username,
            nickname: res[0].nickname,
            id: res[0].id,
            avatar: res[0].avatar
          }
          const token = sign({    // 调用自己写的函数，往token里塞入前端传的以下信息
            id: res[0].id,
            username: res[0].username
          })
          //console.log(token)
          ctx.body = {
            code: 200,
            data: data,
            token: token,
            msg: '登录成功'
          }
        } else {
          ctx.body = {
            code: 500,
            msg: '账号或密码错误'
          }
        }
      } catch (error) {
        ctx.body = {
          code: 500,
          data: error,
          msg: '服务器异常'
        }
      }
    })
    
    
    
    module.exports = {
      userRouter: router
    }